/*
 * @Author: guoju
 * @Date: 2021-12-22 09:24:50
 * @LastEditTime: 2022-01-13 18:13:57
 * @LastEditors: guoju
 * @Description: 填空题
 */

import { useEffect, useState } from 'react';
import { View, Input, Textarea } from '@tarojs/components';
import { INPUT_TYPE } from '@/types/exam.d';
import styles from './index.module.less';

const FillSelect = (props: any) => {
  const {
    extend: {
      max = 100, // 输入框最大输入字符数
      min = 1, // 输入框最小输入字符数
      inputType = 1, // 1: 文本, 2: 整数, 3: 小数
    },
    text,
    setAnswer,
  } = props;

  const [count, setCount] = useState<number>(0);
  // const [inValue, setInValue] = useState<any>();
  
  // useEffect(() => {
  //   // const val = inputType === INPUT_TYPE.TEXT ? text : text === '' ? '' : Number(text);
  //   setInValue(text);
  // }, [text]);

  const onInputValue = (e: any) => {
    const { value } = e.detail;
    let val = value;

    if (inputType === INPUT_TYPE.INTEGER) {
      val = value.replace(/\./g, '').replace(/^0+([^0]\d+)$/, '$1');
      // setInValue(val);
    }

    setAnswer({
      text: val,
      inputType,
    });
  };

  const onTextInputValue = (e: any) => {
    const { value } = e.target;
    setAnswer({
      text: value,
      inputType,
    });
    setCount(value.length);
  };

  return (
    <View className={styles.fillSelectContainer}>
      {(inputType === INPUT_TYPE.INTEGER ||
        inputType === INPUT_TYPE.DECIMAL) && (
        <View className={styles.input}>
          <Input
            type={inputType === INPUT_TYPE.INTEGER ? 'number' : 'digit'}
            value={text}
            placeholder="请输入"
            onInput={onInputValue}
          />
          <View className={styles.tips}>
            *请输入{min}-{max}之间的
            {inputType === INPUT_TYPE.INTEGER ? '整数' : '数字'}
          </View>
        </View>
      )}
      {inputType === INPUT_TYPE.TEXT && (
        <View className={styles.textarea}>
          <Textarea
            value={text}
            maxlength={max}
            onInput={onTextInputValue}
          />
          <View className={styles.tips}>
            *请输入{min}-{max}个字符
          </View>
          <View className={styles.num}>{`${count} / ${max}`}</View>
        </View>
      )}
    </View>
  );
};

export default FillSelect;
